<?php
/**
 * Created by PhpStorm.
 * User: Guo
 * Date: 2017/9/22
 * Time: 21:51
 */

namespace app\back\controller;
use app\back\validate\CommentNew;
use app\common\model\Comment as CommentModel;
use think\Request;
use think\Session;

class Comment extends BaseController
{
    /**
     * 评论
     * @param $id
     * @return \think\response\View
     */
    public function comment($id)
    {
        $comments = CommentModel::getTreeData($id, 'level', 'created_at');
        $this->assign(compact('comments'));
        return view();
    }

    /**
     * 发布评论
     * @param Request $request
     * @return \think\response\Json
     */
    public function addProcess(Request $request)
    {
        (new CommentNew())->goCheck();
        $data = $request->request();
        $model = new CommentModel();
        $model->nickname   = $request->post('nickname', '');
        $model->email      = $request->post('email', '');
        $model->website    = $request->post('website', '');
        $model->comment    = $data['comment'];

        if ($data['submit'] == 'master') { // 评论
            $model->article_id = $request->post('id');
            $model->pid = 0;
        } else if ($data['submit'] == 'reply' && $data['pid'] > 0) { // 回复
            $model->article_id = CommentModel::where('id', $data['pid'])->value('article_id');
            $model->pid = $data['pid'];
        } else {
            return json(['status' => 'failed', 'code'  =>  '10005'], 400);
        }
        if ($login = Session::get('login')) {
            $model->is_anonymous = 0;   // 非匿名发表
            $model->user_id = $login['id'];
        }

        $model->save();
        if ($model->id) {
            return json(['status' => 'success', 'code'  =>  '00000']);
        }
        return json(['status' => 'failed', 'code'  =>  '10000'], 400);

    }

    /**
     * 回复评论
     * @param $id
     * @return \think\response\View
     */
    public function reply($id)
    {
        $this->assign(compact('id'));
        return view();
    }


}